package com.ferryc.controller;

import com.ferryc.entity.Stroage;
import com.ferryc.model.Result;
import com.ferryc.service.IStroageService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * Created by Ferry Chen on 2019-11-06.
 */
@Api(tags = "库存")
@Slf4j
@RestController
@RequestMapping(value = "/stroage", produces = MediaType.APPLICATION_JSON_VALUE)
public class StroageController {


    @Autowired
    private IStroageService stroageService;

    //新增库存变动信息
    @ApiOperation(value = "新增库存", notes = "新增库存")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "商品ID", required = true, dataType = "String"),
            @ApiImplicitParam(name = "money", value = "数量", required = false, dataType = "Number")
    })
    @PostMapping("/add")
    public Result add(@RequestParam(value = "productId") String productId,
                      @RequestParam(value = "count") int count) {
        Stroage stroage = new Stroage();
        stroage.setProductId(productId);
        stroage.setCount(count);
        stroageService.save(stroage);
        return Result.success("ok");
    }

    //更新库存信息
    @ApiOperation(value = "消耗库存", notes = "消耗库存")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "商品ID", required = true, dataType = "String"),
            @ApiImplicitParam(name = "money", value = "数量", required = false, dataType = "Number")
    })
    @PostMapping(value = "/consume")
    public Result consume(@RequestParam(value = "productId") String productId,
                          @RequestParam(value = "count") int count) {
        Stroage stroage = new Stroage();
        stroage.setProductId(productId);
        stroage.setCount(count);
        stroageService.consume(stroage);
        return Result.success("ok");
    }

    //查询库存信息
    @ApiOperation(value = "查询商品库存信息", notes = "查询商品库存信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "商品ID", required = true, dataType = "String")
    })
    @GetMapping("/getByProductId")
    public Result<Stroage> getByProductId(@RequestParam String productId) {
        Stroage stroage = new Stroage();
        stroage.setProductId(productId);
        try {
            List<Stroage> list = stroageService.queryList(stroage);
            if (CollectionUtils.isEmpty(list)) {
                return Result.fail("该商品没有库存");
            }
            return Result.success(list.get(0));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.fail("查询失败");
        }


    }


}
